<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="dialogTitle"
    width="80%"
    :before-close="handleClose"
    class="task-form-dialog"
    :close-on-click-modal="false"
  >
    <div class="dialog-content">
      <component 
        :is="currentFormComponent" 
        ref="formRef"
        v-if="currentFormComponent"
      />
      <div v-else class="no-form">
        <div class="empty-content">
          <i class="el-icon-document-remove" style="font-size: 64px; color: #c0c4cc;"></i>
          <p style="color: #909399; margin: 16px 0 0 0;">未找到对应的表单组件</p>
        </div>
      </div>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ mode === 'view' ? '关闭' : '提交' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getTaskFormComponent, getTaskTypeName } from './index.js'

export default {
  name: 'TaskFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    taskType: {
      type: String,
      default: ''
    },
    taskData: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'edit', // 'view', 'edit', 'add'
      validator: (value) => ['view', 'edit', 'add'].includes(value)
    }
  },
  data() {
    return {
      submitting: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    currentFormComponent() {
      return getTaskFormComponent(this.taskType)
    },
    dialogTitle() {
      const taskName = getTaskTypeName(this.taskType)
      const modeText = {
        view: '查看',
        edit: '编辑',
        add: '新增'
      }
      return `${modeText[this.mode]}${taskName}`
    }
  },
  watch: {
    visible(newVal) {
      if (newVal && this.taskData && Object.keys(this.taskData).length > 0) {
        // 如果有初始数据，填充到表单中
        this.$nextTick(() => {
          if (this.$refs.formRef && this.$refs.formRef.formData) {
            let fdata = {};
            if(this.taskData.seriousHouse){
              fdata = this.taskData.seriousHouse;
            }else if(this.taskData.floodSeasonHouse){
              fdata = this.taskData.floodSeasonHouse;
            }else if(this.taskData.ledgerSubwayProjectstableName){
              fdata = this.taskData.ledgerSubwayProjectstableName;
            }else if(this.taskData.winterHouse){
              fdata = this.taskData.winterHouse;
            }else  if(this.taskData.otherHouse){
              fdata = this.taskData.otherHouse;
            }

            fdata.list =this.taskData.list

            Object.assign(this.$refs.formRef.formData,fdata)

          }
        })
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },
    resetForm() {
      if (this.$refs.formRef && this.$refs.formRef.resetForm) {
        this.$refs.formRef.resetForm()
        this.$message.success('表单已重置')
      }
    },
    async handleSubmit() {
      // if (this.mode === 'view') {
      //   this.handleClose()
      //   return
      // }
      alert(1)
      // 表单验证
      if (this.$refs.formRef && this.$refs.formRef.validate) {
        const isValid = await this.$refs.formRef.validate()
        if (!isValid) {
          this.$message.error('请检查表单输入')
          return
        }
      }

      try {
        this.submitting = true
        
        // 获取表单数据
        const formData = this.$refs.formRef?.formData || {}
        
        // 触发提交事件，由父组件处理具体的提交逻辑
        this.$emit('submit', {
          mode: this.mode,
          taskType: this.taskType,
          formData: formData
        })
        
        this.$message.success('保存成功')
        this.handleClose()
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('保存失败，请重试')
      } finally {
        this.submitting = false
      }
    },
    // 暴露方法供父组件调用
    getFormData() {
      return this.$refs.formRef?.formData
    },
    validateForm() {
      return this.$refs.formRef?.validate()
    }
  }
}
</script>

<style scoped>
.dialog-content {
  min-height: 200px;
  max-height: 70vh;
  overflow-y: auto;
}

.no-form {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.empty-content {
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }
}
</style>